package eoeProject.edenOfEast.page.analyses.analysesRes.component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.calldecorator.AjaxCallDecorator;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import eoeProject.edenOfEast.bean.EOEAnalysesBean;
import eoeProject.edenOfEast.bean.EOEAnalysesResBean;
import eoeProject.edenOfEast.bean.EOEUserBean;
import eoeProject.edenOfEast.core.DBConnector;
import eoeProject.edenOfEast.core.EOEAuthenticatedWebSession;
import eoeProject.edenOfEast.core.SQLMaker;
import eoeProject.edenOfEast.dataBase.DB_EOE_ANALYSES_RES;
import eoeProject.edenOfEast.utils.AnalysesUtils;
import eoeProject.edenOfEast.utils.EOEUtils;

//@AuthorizeInstantiation("ADMIN")
public class AnalysesResListPanel extends Panel {
	private static final long serialVersionUID = 1L;

	private EOEAnalysesBean analyses;
	List<EOEAnalysesResBean> resBeanList = new LinkedList<EOEAnalysesResBean>();
	private Integer visibleDialogId = -1;

	private AnalysesResListPanel instance;

	public AnalysesResListPanel(String id, EOEAnalysesBean parentAnalyses) {
		super(id);
		analyses = parentAnalyses;
		instance = this;

		SQLMaker sql = new SQLMaker(DB_EOE_ANALYSES_RES.TABLE_NAME,
				SQLMaker.SQL_TYPE_SELECT);
		sql.addExpEquals(DB_EOE_ANALYSES_RES.ANALYSES_ID,
				analyses.getAnalysesId());
		sql.addOrderBy(DB_EOE_ANALYSES_RES.RES_NUM, "desc");
		ResultSet rs = DBConnector.getInstance().get(sql.getSQL());
		try {
			while (rs.next()) {
				EOEAnalysesResBean bean = new EOEAnalysesResBean();
				bean.setResId(rs.getInt(DB_EOE_ANALYSES_RES.RES_ID));
				bean.setResNum(rs.getInt(DB_EOE_ANALYSES_RES.RES_NUM));
				bean.setCreateUserId(rs
						.getInt(DB_EOE_ANALYSES_RES.CREATE_USER_ID));
				bean.setRes(rs.getString(DB_EOE_ANALYSES_RES.RES));
				bean.setGJ(rs.getInt(DB_EOE_ANALYSES_RES.GJ));
				bean.setUpdateDate(rs
						.getTimestamp(DB_EOE_ANALYSES_RES.UPDATE_DATE));

				resBeanList.add(bean);
			}
			rs.close();
		} catch (SQLException e) {
			System.out.println("AnalysesTopListPanelException: "
					+ e.getMessage());
		}

		ListView<Object> resList = new ListView<Object>("resList", resBeanList) {
			private static final long serialVersionUID = -6962499153966966392L;

			@SuppressWarnings("rawtypes")
			@Override
			protected void populateItem(ListItem item) {
				final EOEAnalysesResBean bean = (EOEAnalysesResBean) item
						.getModelObject();
				PageParameters parameters = new PageParameters();
				parameters.add("userId", bean.getCreateUserId());
				BookmarkablePageLink<WebPage> accountLink = new BookmarkablePageLink<WebPage>(
						"accountLink",
						eoeProject.edenOfEast.page.account.accountDetailPage.Index.class,
						parameters);
				item.add(new Label("resNum", bean.getResNum().toString()));
				accountLink.add(new Label("createUserName", EOEUtils
						.getUserName(bean.getCreateUserId())));
				item.add(accountLink);
				item.add(new MultiLineLabel("res", bean.getRes()));
				List<EOEUserBean> gjUserList = AnalysesUtils.getGJUserList(bean
						.getResId());
				Label GJ = new Label("GJ", String.valueOf(gjUserList.size()));
				GJ.setOutputMarkupId(true);
				boolean didGJ = false;
				for (EOEUserBean userBean : gjUserList) {
					if (userBean.getUserId().equals(
							EOEAuthenticatedWebSession.getUserId())) {
						didGJ = true;
					}
				}

				GJLink gjLink = new GJLink("gjLink", bean.getResId(),
						EOEAuthenticatedWebSession.getUserId(),
						gjUserList.size());

				DeleteGJLink deleteGjLink = new DeleteGJLink("deleteGjLink",
						AnalysesUtils.getGJId(bean.getResId(),
								EOEAuthenticatedWebSession.getUserId()),
						gjUserList.size());

				if (didGJ) {
					gjLink.setVisible(false);
					deleteGjLink.setVisible(true);
				} else {
					gjLink.setVisible(true);
					deleteGjLink.setVisible(false);
				}
				item.add(gjLink);
				item.add(deleteGjLink);
				AnalysesGJUserListDialogPanel gjUserListDialogPanel = new AnalysesGJUserListDialogPanel(
						"gjUserListDialogPanel", bean.getResId(), instance);
				gjUserListDialogPanel.setOutputMarkupId(true);
				if (visibleDialogId == item.getIndex())
					gjUserListDialogPanel.setVisible(true);
				else
					gjUserListDialogPanel.setVisible(false);

				GJUserListDialogLink gjUserListDialogLink = new GJUserListDialogLink(
						"gjUserListDialogLink", item.getIndex());
				gjUserListDialogLink.add(GJ);
				item.add(gjUserListDialogLink);
				item.add(gjUserListDialogPanel);

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 H時m分s秒");
				item.add(new Label("updateDate", sdf.format(bean
						.getUpdateDate())));

			}

		};
		add(resList);
	}

	public void closeDialog() {
		visibleDialogId = -1;
	}

	private class GJLink extends AjaxLink<Void> {

		Integer resId;
		Integer userId;
		Integer gjCount;

		private static final long serialVersionUID = -2942520388218435030L;

		public GJLink(String id, Integer resId, Integer userId, Integer gjCount) {
			super(id);

			this.resId = resId;
			this.userId = userId;
			this.gjCount = gjCount;
		}

		@Override
		public void onClick(AjaxRequestTarget target) {
			setResponsePage(target.getPage());
			AnalysesUtils.doGJ(resId, userId, gjCount);
			target.add();

		}

	};

	private class DeleteGJLink extends AjaxLink<Void> {

		Integer gjId;
		Integer gjCount;

		private static final long serialVersionUID = -2942520388218435030L;

		public DeleteGJLink(String id, Integer gjId, Integer gjCount) {
			super(id);

			this.gjId = gjId;
			this.gjCount = gjCount;

		}

		@Override
		public void onClick(AjaxRequestTarget target) {
			setResponsePage(target.getPage());
			AnalysesUtils.deleteGJ(gjId);
			target.add();

		}

	};

	private class GJUserListDialogLink extends AjaxLink<Void> {

		Integer itemId;

		private static final long serialVersionUID = -2942520388218435030L;

		public GJUserListDialogLink(String id, Integer itemId) {
			super(id);
			this.itemId = itemId;
		}

		@Override
		public void onClick(AjaxRequestTarget target) {
			setResponsePage(target.getPage());
			visibleDialogId = itemId;

			target.add();
		}

		@Override
		protected IAjaxCallDecorator getAjaxCallDecorator() {
			return new AjaxCallDecorator() {
				/**
				 *
				 */
				private static final long serialVersionUID = 1L;

				@Override
				public CharSequence decorateScript(Component c,
						CharSequence script) {
					return super.decorateScript(c, "savelocate(); " + script);
				}
			};
		}

	};
}
